package sdu.ltp.resolve;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * 抽象解析类
 * 
 * @author ljh_2015
 *
 */
public abstract class AbstractResolver extends DefaultHandler {

    private final Logger logger = Logger.getLogger(AbstractResolver.class);
    ArrayList<Node> nodes = new ArrayList<>();
    /**
     * 将原始数据进行解析，并封装成继承了OriginData的D类
     * @param base
     * @return
     */
    public void resolve(BaseData base) {
	SAXParserFactory factory = SAXParserFactory.newInstance();
	SAXParser parser;
	try {
	    parser = factory.newSAXParser();
	    parser.parse(base.getBody(), this);
	} catch (Exception e) {
	    logger.error("error resolve!");
	} 
	
    }
    
    public abstract Map<String,List<Node>> resolveData(BaseData base);
    
    
    public class Node {
	
	/**
	 *  词id
	 */
	int id;
	
	/**
	 * 内容
	 */
	String text;
	/**
	 *  词性
	 */
	String pos;
	
	/**
	 *  依存关系
	 */
	String relate;
	
	/**
	 *  父级元素
	 */
	int parent;

	public int getId() {
	    return id;
	}

	public void setId(int id) {
	    this.id = id;
	}

	public String getText() {
	    return text;
	}

	public void setText(String text) {
	    this.text = text;
	}

	public String getPos() {
	    return pos;
	}

	public void setPos(String pos) {
	    this.pos = pos;
	}

	public String getRelate() {
	    return relate;
	}

	public void setRelate(String relate) {
	    this.relate = relate;
	}

	public int getParent() {
	    return parent;
	}

	public void setParent(int parent) {
	    this.parent = parent;
	}
	
	
    }


    @Override
    public void startElement(String uri, String localName, String qName,
	    Attributes attributes) throws SAXException {
	super.startElement(uri, localName, qName, attributes);
	if("word".equals(qName)) {
	    Node n = new Node();
	    n.id = Integer.parseInt(attributes.getValue("id"));
	    n.text = attributes.getValue("cont");
	    n.pos = attributes.getValue("pos");
	    n.parent = Integer.parseInt(attributes.getValue("parent"));
	    n.relate = attributes.getValue("relate");
	    //注入基于Node节点统计
	    StatisticsTemplate.statisticsNode(n);
	    nodes.add(n);
	}
    }

}
